<!doctype html>



  


<html class="theme-next muse use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  

  

  

  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.1" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="Android," />





  <link rel="alternate" href="/atom.xml" title="Martin's Blog" type="application/atom+xml" />




  <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=5.1.1" />






<meta name="description" content="AlarmManager是Android系统里管理RTC(Real Time Clock)的模块，可以在CPU休眠时正常运行，在预设的时间到达时，通过中断唤醒CPU。所以，AlarmManager经常用在需要长时间定时的需求上。 如果，有比较多的定时任务需要AlarmManager来管理，如何才能方便地区分这些定时任务呢？">
<meta name="keywords" content="Android">
<meta property="og:type" content="article">
<meta property="og:title" content="Android之AlarmManager如何区分不同的定时器">
<meta property="og:url" content="http://martint.oschina.io/2015/12/26/Android之AlarmManager如何区分不同的定时器/index.html">
<meta property="og:site_name" content="Martin&#39;s Blog">
<meta property="og:description" content="AlarmManager是Android系统里管理RTC(Real Time Clock)的模块，可以在CPU休眠时正常运行，在预设的时间到达时，通过中断唤醒CPU。所以，AlarmManager经常用在需要长时间定时的需求上。 如果，有比较多的定时任务需要AlarmManager来管理，如何才能方便地区分这些定时任务呢？">
<meta property="og:updated_time" content="2017-06-18T01:50:53.000Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Android之AlarmManager如何区分不同的定时器">
<meta name="twitter:description" content="AlarmManager是Android系统里管理RTC(Real Time Clock)的模块，可以在CPU休眠时正常运行，在预设的时间到达时，通过中断唤醒CPU。所以，AlarmManager经常用在需要长时间定时的需求上。 如果，有比较多的定时任务需要AlarmManager来管理，如何才能方便地区分这些定时任务呢？">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Muse',
    sidebar: {"position":"left","display":"post","offset":12,"offset_float":0,"b2t":false,"scrollpercent":false},
    fancybox: true,
    motion: true,
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://martint.oschina.io/2015/12/26/Android之AlarmManager如何区分不同的定时器/"/>





  <title>Android之AlarmManager如何区分不同的定时器 | Martin's Blog</title>
  














</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail ">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Martin's Blog</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">每天进步一点</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">
    <link itemprop="mainEntityOfPage" href="http://martint.oschina.io/2015/12/26/Android之AlarmManager如何区分不同的定时器/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Martin Tang">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Martin's Blog">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">Android之AlarmManager如何区分不同的定时器</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2015-12-26T12:28:12+08:00">
                2015-12-26
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/技术笔记/" itemprop="url" rel="index">
                    <span itemprop="name">技术笔记</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
              <span class="post-comments-count">
                <span class="post-meta-divider">|</span>
                <span class="post-meta-item-icon">
                  <i class="fa fa-comment-o"></i>
                </span>
                <a href="/2015/12/26/Android之AlarmManager如何区分不同的定时器/#comments" itemprop="discussionUrl">
                  <span class="post-comments-count ds-thread-count" data-thread-key="2015/12/26/Android之AlarmManager如何区分不同的定时器/" itemprop="commentCount"></span>
                </a>
              </span>
            
          

          
          

          

          

          

        </div>
      </header>
    

    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>AlarmManager是Android系统里管理RTC(Real Time Clock)的模块，可以在CPU休眠时正常运行，在预设的时间到达时，通过中断唤醒CPU。所以，AlarmManager经常用在需要长时间定时的需求上。</p>
<p>如果，有比较多的定时任务需要AlarmManager来管理，如何才能方便地区分这些定时任务呢？<br><a id="more"></a></p>
<p>对于AlarmManager来说，肯定通过PendingIntent来区分。那么，PendingIntent通过什么来区分呢？</p>
<p>一般在AlarmManager中，PendingIntent都是通过<strong>PendingIntent.getBroadcast</strong>来获取的，那我们来看一下<strong>getBroadcast</strong>的参数：<br><code>public static PendingIntent getBroadcast(Context context, int requestCode, Intent intent, int flags)</code></p>
<p><strong>context</strong>不用考虑，<strong>flags</strong>表示AlarmManager对该intent的控制，也不用考虑。<strong>intent</strong>显然是可以用于区分<strong>pendingIntent</strong>的，但是<strong>pendingIntent</strong>是用<a href="http://developer.android.com/reference/android/content/Intent.html#filterEquals(android.content.Intent)" target="_blank" rel="external">filterEquals(Intent)</a>来比较<strong>intent</strong>的，而<a href="http://developer.android.com/reference/android/content/Intent.html#filterEquals(android.content.Intent)" target="_blank" rel="external">filterEquals(Intent)</a>只比较<em>action</em>，<em>data</em>，<em>type</em>，<em>class</em>和<em>categories</em>，不会比较任何<em>extra data</em>的。</p>
<p>如果我们有固定个数的定时任务，我们可以为每个定时任务定义一个action，然后对应一个intent和一个pendingIntent。对于BoardcastReceiver，我们仅对于这些action进行接收。</p>
<p>但是，如果我们的定时任务个数不确定呢？或者，我们想使我们代码的耦合性更好呢？</p>
<p>我们可能期望BoardcastReceiver不用对action进行过滤，我们可能在代码中比较方便的用extra data来标示逻辑，这种情况下，<strong>intent</strong>就不能区分<strong>pendingIntent</strong>了。</p>
<p>我们注意到，还有一个<strong>requestCode</strong>参数，这个参数有的文档里写的是现在没有用，但是其实是可以区分<strong>pendingIntent</strong>的<sup><a href="#ref1">[1]</a></sup>。</p>
<p>下面是个代码片段：<br><figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div></pre></td><td class="code"><pre><div class="line">...</div><div class="line">    mAlarmMgr = (AlarmManager) mContext.getSystemService(Context.ALARM_SERVICE);</div><div class="line">    mAlarmReceiver = <span class="keyword">new</span> AlarmReceiver();</div><div class="line">    IntentFilter intentFilter = <span class="keyword">new</span> IntentFilter(ACTION);</div><div class="line">    mContext.registerReceiver(mAlarmReceiver, intentFilter);</div><div class="line">...</div><div class="line"></div><div class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">startAlarmTask</span><span class="params">(<span class="keyword">long</span> time, <span class="keyword">long</span> interval, <span class="keyword">int</span> id)</span> </span>&#123;</div><div class="line">        <span class="keyword">try</span> &#123;</div><div class="line">            Intent intent = <span class="keyword">new</span> Intent(ACTION);</div><div class="line">            intent.putExtra(<span class="string">"id"</span>, id);</div><div class="line">            PendingIntent pendingIntent = PendingIntent.getBroadcast(mContext, id, intent, PendingIntent.FLAG_UPDATE_CURRENT);  </div><div class="line">            <span class="keyword">long</span> tiggertTime = System.currentTimeMillis() + time;</div><div class="line">            mAlarmMgr.setRepeating(AlarmManager.RTC_WAKEUP, tiggertTime, interval, pendingIntent);</div><div class="line">        &#125; <span class="keyword">catch</span> (Exception e) &#123;</div><div class="line">            Log.i(LogConstants.HEART_TAG, <span class="string">"startAlarmTask error id = "</span> + id);</div><div class="line">        &#125;</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    <span class="keyword">private</span> <span class="class"><span class="keyword">class</span> <span class="title">AlarmReceiver</span> <span class="keyword">extends</span> <span class="title">BroadcastReceiver</span> </span>&#123; </div><div class="line">        <span class="meta">@Override</span></div><div class="line">        <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">onReceive</span><span class="params">(Context context, Intent intent)</span> </span>&#123;</div><div class="line">            <span class="keyword">try</span> &#123;</div><div class="line">                <span class="keyword">int</span> id = intent.getIntExtra(<span class="string">"id"</span>, -<span class="number">1</span>);</div><div class="line">                ...</div><div class="line">            &#125; <span class="keyword">catch</span> (Exception e) &#123;</div><div class="line">                e.printStackTrace();</div><div class="line">            &#125;</div><div class="line">        &#125;</div><div class="line">    &#125;</div></pre></td></tr></table></figure></p>
<hr>
<p>参考：</p>
<p>[1]. <a id="ref1"><a href="http://zhiweiofli.iteye.com/blog/1972513" target="_blank" rel="external">Android开发陷阱：利用PendingIntent传递唯一的Intent</a></a></p>

      
    </div>

    <div>
      
        

      
    </div>

    <div>
      
        

      
    </div>

    <div>
      
        

      
    </div>

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/Android/" rel="tag"># Android</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2015/12/23/Mac下如何全方位访问外网/" rel="next" title="Mac下如何全方位访问外网">
                <i class="fa fa-chevron-left"></i> Mac下如何全方位访问外网
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2016/01/17/《你的时间有限，不要为别人而活》读书笔记/" rel="prev" title="《你的时间有限，不要为别人而活》读书笔记">
                《你的时间有限，不要为别人而活》读书笔记 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          
  <div class="comments" id="comments">
    
      <div class="ds-thread" data-thread-key="2015/12/26/Android之AlarmManager如何区分不同的定时器/"
           data-title="Android之AlarmManager如何区分不同的定时器" data-url="http://martint.oschina.io/2015/12/26/Android之AlarmManager如何区分不同的定时器/">
      </div>
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      

      <section class="site-overview sidebar-panel sidebar-panel-active">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image"
               src="/images/avatar.gif"
               alt="Martin Tang" />
          <p class="site-author-name" itemprop="name">Martin Tang</p>
           
              <p class="site-description motion-element" itemprop="description"></p>
          
        </div>
        <nav class="site-state motion-element">

          
            <div class="site-state-item site-state-posts">
              <a href="/archives/">
                <span class="site-state-item-count">33</span>
                <span class="site-state-item-name">日志</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-categories">
              <a href="/categories/index.html">
                <span class="site-state-item-count">4</span>
                <span class="site-state-item-name">分类</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-tags">
              <a href="/tags/index.html">
                <span class="site-state-item-count">8</span>
                <span class="site-state-item-name">标签</span>
              </a>
            </div>
          

        </nav>

        
          <div class="feed-link motion-element">
            <a href="/atom.xml" rel="alternate">
              <i class="fa fa-rss"></i>
              RSS
            </a>
          </div>
        

        <div class="links-of-author motion-element">
          
        </div>

        
        

        
        

        


      </section>

      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright" >
  
  &copy; 
  <span itemprop="copyrightYear">2017</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Martin Tang</span>
</div>


<div class="powered-by">
  由 <a class="theme-link" href="https://hexo.io">Hexo</a> 强力驱动
</div>

<div class="theme-info">
  主题 -
  <a class="theme-link" href="https://github.com/iissnan/hexo-theme-next">
    NexT.Muse
  </a>
</div>


        

        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>

  
  <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.1"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.1"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.1"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.1"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.1"></script>



  

  
    
  

  <script type="text/javascript">
    var duoshuoQuery = {short_name:"martintang"};
    (function() {
      var ds = document.createElement('script');
      ds.type = 'text/javascript';ds.async = true;
      ds.id = 'duoshuo-script';
      ds.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') + '//static.duoshuo.com/embed.js';
      ds.charset = 'UTF-8';
      (document.getElementsByTagName('head')[0]
      || document.getElementsByTagName('body')[0]).appendChild(ds);
    })();
  </script>

  
    
    
    <script src="/lib/ua-parser-js/dist/ua-parser.min.js?v=0.7.9"></script>
    <script src="/js/src/hook-duoshuo.js"></script>
  
















  





  

  

  

  

  

  

</body>
</html>
